<template>
  <view class="dropdown-item flex-item">
    <view class="dropdown-item-show" @click="opend">
      <text class="mr5">{{ getText(modelValue) }}</text>
      <uni-icons :type="show ? 'up' : 'down'" color="#666" size="12"></uni-icons>
    </view>
    <view class="dropdown-popup" :class="{ active: show }" @click="closed">
      <view class="dropdown-popup-body">
        <view class="dropdown-popup-list" v-if="options.length">
          <view class="dropdown-popup-list-item"
                v-for="(item, index) in options"
                :key="index"
                :class="{ active: item.value === modelValue }"
                @click="onConfirm(item.value)">
            {{ item.text }}
          </view>
        </view>
        <slot/>
      </view>
    </view>
  </view>
</template>

<script setup>
import {ref, onMounted} from 'vue';

const props = defineProps({
  modelValue: {
    type: [String, Number, Array],
    default: '1',
  },
  options: {
    type: Array,
    default: () => [],
  },
  title: {
    type: String,
    default: '',
  },
  placeholder: {
    type: String,
    default: '',
  },
});
const emit = defineEmits(['change']);

const show = ref(false);

const opend = () => {
  if (show.value) {
    closed();
    return;
  }
  uni.$emit('closeDropdown');
  show.value = true;
  uni.$on('closeDropdown', () => {
    closed();
  });
};

const closed = () => {
  uni.$off('closeDropdown');
  show.value = false;
};

const getText = (val) => {
  const ob = props.options.find(e => e.value === val);
  return ob ? ob.text : props.title || props.placeholder;
};

const onConfirm = (date) => {
  emit('update:modelValue', date);
};
</script>

<style lang="scss" scoped>
.dropdown-item {
  text-align: center;

  .dropdown-item-show {
    font-size: 28rpx;
  }

  .uni-icons {
    margin-left: 8rpx;
  }

  .dropdown-popup {
    position: fixed;
    left: 0;
    top: -100vh;
    width: 100%;
    height: 100vh;
    background: rgba(0, 0, 0, 0.7);
    transition: all 0.2s;
    opacity: 0;
    z-index: -1;

    &.active {
      opacity: 1;
      z-index: 99;
      top: auto;
    }
  }

  .dropdown-popup-body {
    width: 100%;
    padding: 6px 0;
    background: #fff;
  }

  .dropdown-popup-list-item {
    font-size: 26rpx;
    padding: 6px 15px;
    text-align: left;
    color: #333;

    &.active {
      color: var(--color);
    }
  }
}
</style>